package com.zx.security.block.handle;

import com.alibaba.fastjson2.JSON;
import com.zx.core.constant.TokenConstants;
import com.zx.core.wrapper.ResponseWrapper;
import com.zx.security.block.service.ICustomTokenService;
import com.zx.security.common.model.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * <p>
 * description: 注销处理类 <br>
 * create: 2024-08-21 00:15
 * </p>
 *
 * @author zhou  xun
 */
@Component
@RequiredArgsConstructor
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    private final ICustomTokenService iCustomTokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication)
            throws IOException {
        // 获取token
        String token = request.getHeader(TokenConstants.AUTHENTICATION);
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        LoginUser loginUser = iCustomTokenService.getLoginUser(token);
        if (!Objects.isNull(loginUser)) {
            // 删除用户缓存记录
            iCustomTokenService.delLoginUser(token);
        }
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("utf-8");
        ResponseWrapper result = new ResponseWrapper();
        response.getWriter().print(JSON.toJSONString(result));

    }
}
